﻿using System;
using System.Security.Permissions;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Security;
using Microsoft.SharePoint.Utilities;
using Microsoft.SharePoint.Workflow;

namespace Docsbox.DocumentsEventReceiver
{
    /// <summary>
    /// List Item Events
    /// </summary>
    public class DocumentsEventReceiver : SPItemEventReceiver
    {
       /// <summary>
       /// An item is being added.
       /// </summary>
       public override void ItemAdding(SPItemEventProperties properties)
       {
           base.ItemAdding(properties);
       }

       /// <summary>
       /// An item is being updated.
       /// </summary>
       public override void ItemUpdating(SPItemEventProperties properties)
       {
           base.ItemUpdating(properties); 
           string oldAccount = Common.ConvertFieldToString(properties.BeforeProperties[Common.FieldAccountLookup],
                                                            FieldType.Text);
           string newAccount = Common.ConvertFieldToString(properties.AfterProperties[Common.FieldAccountLookup],
                                                           FieldType.Text);
           SPList accounts = properties.Web.Lists[Common.ListAccounts];
           string oldStatus = GetAccountStatusById(accounts,oldAccount);
           string newStatus = GetAccountStatusById(accounts,newAccount);

           //associated account is changed
           if (!oldAccount.Equals(newAccount, StringComparison.CurrentCultureIgnoreCase) && !string.IsNullOrEmpty(oldAccount))
           {
               if(oldStatus.Equals(Common.StatusCompleted))
               {

                   properties.Cancel = true;
                   properties.Status = SPEventReceiverStatus.CancelWithError;
                   properties.ErrorMessage = "The document associated account is marked as completed, you cannot remove the document from the associated account.";
               }
               if (newStatus.Equals(Common.StatusCompleted))
               {

                   properties.Cancel = true;
                   properties.Status = SPEventReceiverStatus.CancelWithError;
                   properties.ErrorMessage = "The account you want to associate is already marked as Completed, no changes can be made to Completed Account.";
               }
           }

       }

        private string GetAccountStatusById(SPList accounts, string accountId)
        {
            SPListItem account = accounts.GetItemById(Convert.ToInt32(accountId));
            string status = Common.ConvertFieldToString(account[Common.FieldAccountStatus], FieldType.Lookup);
            return status;
        }

        /// <summary>
       /// An item was added.
       /// </summary>
       public override void ItemAdded(SPItemEventProperties properties)
       {
           base.ItemAdded(properties);
           //name the Title field to the name of the document
           string documentName = properties.ListItem.Name;
           properties.ListItem["Title"] = documentName;
           properties.ListItem["IsNew"] = 1;
           EventFiringEnabled = false;
           properties.ListItem.Update();
           EventFiringEnabled = true;
       }

       /// <summary>
       /// An item was updated.
       /// </summary>
       public override void ItemUpdated(SPItemEventProperties properties)
       {
           base.ItemUpdated(properties);
           SPList documents = properties.List;
           SPListItem item = properties.ListItem;
           //check the account field is set or still empty
           //if the account field is changed, move the document to new location
           string oldAccount = Common.ConvertFieldToString(properties.BeforeProperties[Common.FieldAccountLookup],
                                                           FieldType.Text);
           string newAccount = Common.ConvertFieldToString(properties.AfterProperties[Common.FieldAccountLookup],
                                                           FieldType.Text);
           if (!newAccount.Equals(oldAccount) && string.IsNullOrEmpty(oldAccount))
           {
               item["IsNew"] = 0;
               EventFiringEnabled = false;
               item.Update();
               EventFiringEnabled = true;
           }

           if(!newAccount.Equals(oldAccount) && !string.IsNullOrEmpty(newAccount))
           {
               SPList accounts = properties.Web.Lists[Common.ListAccounts];
               SPListItem account = accounts.GetItemById(Convert.ToInt32(newAccount));

               if(account!= null)
               {
                   string title = Common.ConvertFieldToString(account[Common.FieldMTFNo], FieldType.Text);
                   string folderName = title.Substring(title.Length - 2);

                    bool folderCreated = false;

                    SPListItemCollection folders = documents.Folders;
                    foreach (SPListItem spListItem in folders)
                    {
                        if (spListItem.Name.Equals(folderName))
                        {
                            folderCreated = true;
                            break;
                        }
                    }

                    if (!folderCreated)
                    {

                        SPListItem folder = documents.Items.Add(documents.RootFolder.ServerRelativeUrl,
                                                                SPFileSystemObjectType.Folder, null);
                        if (folder != null)
                        {
                            folder["Name"] = folderName;
                            folder.Update();
                        }
                    }

                    SPFile file = documents.ParentWeb.GetFile(item.Url);

                    string destinationUrl = string.Format("{0}/{1}/{2}",
                                                            item.Url.Substring(0, item.Url.IndexOf('/')), folderName, item.Name);
                   EventFiringEnabled = false;
                    file.MoveTo(destinationUrl, true);
                   EventFiringEnabled = true;                   
               }


           }
       }

       public override void ItemDeleting(SPItemEventProperties properties)
       {
           base.ItemDeleting(properties);
           int accountId = Common.ConvertLookupFieldToId(properties.ListItem[Common.FieldAccountLookup]);

           if(accountId > 0)
           {
               SPList accounts = properties.Web.Lists[Common.ListAccounts];

               string status = GetAccountStatusById(accounts, accountId.ToString());

               if(status.Equals(Common.StatusCompleted, StringComparison.CurrentCultureIgnoreCase))
               {
                   properties.Cancel = true;
                   properties.Status = SPEventReceiverStatus.CancelWithError;
                   properties.ErrorMessage = "The account associated to this document is marked as Completed, you cannot delete this document from this account.";
                   
               }
           }
       }
    }
}
